<template>
  <div class="approval-page">
    <div class="wrap">
      <!-- 顶部步骤条 -->
      <StepBar :steps="steps" :current-step="currentStep" />

      <div class="content">
        <!-- 左侧：基本信息、申请信息 -->
        <div class="left">
          <div class="card">
            <div class="card-title">基本信息</div>
            <el-descriptions :column="2" border label-class-name="desc-label" class="desc">
              <el-descriptions-item label="单据编号">{{ formData.elderlyNo }}</el-descriptions-item>
              <el-descriptions-item label="老人姓名">{{ formData.elderlyName }}</el-descriptions-item>
              <el-descriptions-item label="老人身份证号">{{ formData.elderlyIdCard }}</el-descriptions-item>
              <el-descriptions-item label="联系方式">{{ formData.contact }}</el-descriptions-item>
              <el-descriptions-item label="费用期限">{{ formData.feePeriod }}</el-descriptions-item>
              <el-descriptions-item label="护理等级">{{ formData.careLevel }}</el-descriptions-item>
              <el-descriptions-item label="入住床位">{{ formData.bedNumber }}</el-descriptions-item>
              <el-descriptions-item label="签约合同">
                {{ formData.contract }}
                <el-button link type="primary" size="small" style="margin-left: 8px" @click="viewContract">查看</el-button>
              </el-descriptions-item>
              <el-descriptions-item label="养老顾问">{{ formData.consultant }}</el-descriptions-item>
              <el-descriptions-item label="护理员">{{ formData.caregiver }}</el-descriptions-item>
            </el-descriptions>
          </div>

          <div class="card">
            <div class="card-title">申请信息</div>
            <el-descriptions :column="2" border label-class-name="desc-label" class="desc">
              <el-descriptions-item label="退住日期">{{ formData.checkoutDate }}</el-descriptions-item>
              <el-descriptions-item label="退住原因">{{ formData.checkoutReason }}</el-descriptions-item>
              <el-descriptions-item label="备注" :span="2">
                {{ formData.remark }}
              </el-descriptions-item>
              <el-descriptions-item label="申请人">{{ formData.applicantName }}</el-descriptions-item>
              <el-descriptions-item label="申请时间">{{ formData.submitTime }}</el-descriptions-item>
            </el-descriptions>
          </div>
        </div>

        <!-- 右侧：审批结果、操作记录 -->
        <div class="right">
          <div class="card">
            <div class="card-title">审批结果</div>
            <div class="result-group">
              <div class="label"><span class="required">*</span>审批结果</div>
              <el-radio-group v-model="approveResult">
                <el-radio label="pass">审批通过</el-radio>
                <el-radio label="reject">审批拒绝</el-radio>
              </el-radio-group>
            </div>
            <div class="result-group">
              <div class="label"><span class="required">*</span>审批意见</div>
              <el-input 
                v-model="approveComment" 
                type="textarea" 
                :rows="5" 
                maxlength="200" 
                show-word-limit 
                placeholder="请输入" 
              />
            </div>
          </div>

          <div class="card">
            <div class="card-title">操作记录</div>
            <div class="timeline">
              <div class="timeline-item">
                <div class="timeline-icon success">✓</div>
                <div class="timeline-content">
                  <div class="timeline-header">
                    <div class="timeline-title">护理员a发起申请</div>
                    <div class="timeline-date">2048-10-15 09:00:00</div>
                  </div>
                  <div class="timeline-user">
                    护理员a
                    <el-tag size="small" type="success">已发起</el-tag>
                  </div>
                </div>
              </div>
              <div class="timeline-item">
                <div class="timeline-icon pending">⏱</div>
                <div class="timeline-content">
                  <div class="timeline-header">
                    <div class="timeline-title">(待处理) 审批-申请审批</div>
                  </div>
                  <div class="timeline-user">
                    退住审批员
                    <el-tag size="small" type="info">审批中</el-tag>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 底部操作按钮 -->
      <div class="bottom-actions">
        <el-button @click="handleBack">返回</el-button>
        <el-button type="primary" @click="handleSubmit">提交</el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import StepBar from '@/components/StepBar/index.vue'
import { submitApproval, getCheckoutApplicationDetail } from '@/api/system/approval'
import { getContractByElderlyId } from '@/api/system/out_management'

const router = useRouter()
const route = useRoute()

// 步骤条数据
const steps = ['申请退住', '申请审批', '解除合同', '调整账单', '账单审批', '退住审批', '费用清算']

// 表单数据
const approveResult = ref('pass')
const approveComment = ref('')

// 当前步骤
const currentStep = ref(1)

// 从sessionStorage读取的申请数据
const formData = ref({
  elderlyNo: 'TZ204810101S000001',
  elderlyName: '高启强',
  elderlyIdCard: '230203197702221029',
  contact: '13898988888',
  feePeriod: '2048-10-10 —— 2049-10-10',
  careLevel: '特级护理等级',
  bedNumber: '101床位',
  contract: '高启强长住合同.pdf',
  consultant: '顾廷烨',
  caregiver: '盛长柏、盛明兰、盛如兰',
  checkoutDate: '2048-10-15',
  checkoutReason: '服务不周',
  remark: '已和家属沟通过，若高龄先生回归后，将重新办理入住',
  applicantName: '顾廷烨',
  submitTime: '2048-10-05 15:00:00'
})

// 当前用户信息
const currentUser = ref({
  nickName: ''
})

// 页面加载时从URL参数或sessionStorage读取数据
onMounted(async () => {
  console.log('=== 审批页面加载开始 ===')
  console.log('URL参数:', route.query)
  console.log('完整路由信息:', route)
  
  // 获取当前用户信息
  try {
    const userInfo = JSON.parse(sessionStorage.getItem('userInfo') || '{}')
    currentUser.value.nickName = userInfo.nickName || '当前用户'
    console.log('当前用户信息:', currentUser.value)
  } catch (error) {
    console.error('获取用户信息失败:', error)
    currentUser.value.nickName = '当前用户'
  }
  
  // 优先从后端API获取数据（根据业务ID查询）
  console.log('=== 优先从后端API获取数据 ===')
  
  let checkoutData = null
  if (route.query.id) {
    const businessId = route.query.id
    console.log('使用业务ID从后端获取数据:', businessId)
    
    try {
      const response = await getCheckoutApplicationDetail(businessId)
      console.log('后端返回的申请详情:', response)
      
      if (response.code === 200 && response.data) {
        const appData = response.data
        console.log('解析后的申请数据:', appData)
        
        // 使用后端数据更新表单
        formData.value = {
          elderlyNo: appData.checkOutNo || 'COUT' + businessId,
          elderlyName: appData.elderlyName || '未知老人',
          elderlyIdCard: appData.elderlyIdCard || '未知身份证',
          contact: appData.elderlyContact || '未知联系方式',
          feePeriod: (appData.feeStartDate && appData.feeEndDate) ? 
            `${appData.feeStartDate} 至 ${appData.feeEndDate}` : '未知费用期限',
          careLevel: appData.careLevel || '未知护理等级', // 使用SQL查询的护理等级
          bedNumber: appData.bedNumber || '未知床位',
          contract: appData.contractName || '未知合同',
          consultant: appData.caregiverName || '未知顾问',
          caregiver: appData.caregiverName || '未知护理员',
          checkoutDate: appData.checkOutDate || '未知退住日期',
          checkoutReason: appData.checkOutReason || '未知退住原因',
          remark: appData.remark || '无备注',
          applicantName: '护理员a',
          submitTime: appData.createTime || new Date().toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit',
            hour12: false
          }).replace(/\//g, '-')
        }
        
        console.log('使用后端数据更新表单:', formData.value)
        
        // 合同信息已经在SQL查询中获取，直接使用
        console.log('合同信息:', appData.contractName)
        if (appData.contractName) {
          formData.value.contract = appData.contractName
          console.log('使用SQL查询的合同信息:', appData.contractName)
        } else {
          // 如果SQL查询没有合同信息，尝试通过API获取
          if (appData.elderlyId) {
            try {
              console.log('=== SQL查询无合同信息，尝试API获取 ===')
              console.log('老人ID:', appData.elderlyId)
              
              const contractResponse = await getContractByElderlyId(appData.elderlyId)
              console.log('合同API响应:', contractResponse)
              
              if (contractResponse.code === 200 && contractResponse.data && contractResponse.data.contractName) {
                console.log('合同数据:', contractResponse.data)
                console.log('合同名称:', contractResponse.data.contractName)
                formData.value.contract = contractResponse.data.contractName
              } else {
                console.log('未找到合同数据，显示无合同')
                formData.value.contract = '无合同'
              }
              
              console.log('最终合同显示:', formData.value.contract)
              console.log('=== 合同信息获取完成 ===')
            } catch (contractError) {
              console.error('获取合同信息失败:', contractError)
              formData.value.contract = '获取失败'
            }
          } else {
            console.log('没有老人ID，无法获取合同信息')
            formData.value.contract = '无合同'
          }
        }
        
        console.log('=== 数据加载完成，审批页面将显示后端查询的数据 ===')
        return // 成功获取后端数据，直接返回
      }
    } catch (apiError) {
      console.error('后端API调用失败:', apiError)
      console.log('=== 后端API失败，尝试从sessionStorage获取数据 ===')
    }
    
    // 如果后端API失败，尝试从sessionStorage获取数据
    const storageKey = `checkout_approval_data_${businessId}`
    console.log('使用存储键:', storageKey)
    
    checkoutData = sessionStorage.getItem(storageKey)
    console.log('从特定存储键获取的数据:', checkoutData)
    
    // 如果特定存储键没有数据，尝试通用存储键
    if (!checkoutData) {
      console.log('特定存储键没有数据，尝试通用存储键')
      checkoutData = sessionStorage.getItem('checkout_approval_data')
      console.log('从通用存储键获取的数据:', checkoutData)
    }
  } else {
    console.log('没有业务ID，使用通用存储键')
    checkoutData = sessionStorage.getItem('checkout_approval_data')
    console.log('从通用存储键获取的退住申请数据:', checkoutData)
  }
  
  if (checkoutData) {
    try {
      const data = JSON.parse(checkoutData)
      console.log('解析后的表单数据:', data)
      
      // 使用sessionStorage数据更新表单
      formData.value = {
        elderlyNo: data.elderlyNo || 'COUT' + Date.now().toString().slice(-4),
        elderlyName: data.elderlyName || '未知老人',
        elderlyIdCard: data.elderlyIdCard || '未知身份证',
        contact: data.contact || '未知联系方式',
        feePeriod: data.feePeriod || '未知费用期限',
        careLevel: data.careLevel || '未知护理等级',
        bedNumber: data.bedNumber || '未知床位',
        contract: data.contract || '未知合同',
        consultant: data.consultant || '未知顾问',
        caregiver: data.caregiver || '未知护理员',
        checkoutDate: data.checkoutDate || '未知退住日期',
        checkoutReason: data.checkoutReason || '未知退住原因',
        remark: data.remark || '无备注',
        applicantName: data.applicantName || '护理员a',
        submitTime: data.submitTime || new Date().toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit',
          second: '2-digit',
          hour12: false
        }).replace(/\//g, '-')
      }
      
      console.log('使用sessionStorage数据更新表单:', formData.value)
      console.log('=== 数据加载完成，审批页面将显示提交的表单数据 ===')
      
    } catch (error) {
      console.error('解析sessionStorage数据失败:', error)
      console.log('=== 解析失败，尝试从后端获取数据 ===')
      
      // 如果sessionStorage解析失败，尝试从后端获取
      if (route.query.id) {
        try {
          const response = await getCheckoutApplicationDetail(route.query.id)
          console.log('后端返回的申请详情:', response)
          
          if (response.code === 200 && response.data) {
            const appData = response.data
            console.log('解析后的申请数据:', appData)
            
            // 使用后端数据更新表单
            formData.value = {
              elderlyNo: appData.checkOutNo || 'COUT' + route.query.id,
              elderlyName: appData.elderlyName || '未知老人',
              elderlyIdCard: appData.elderlyIdCard || '未知身份证',
              contact: appData.elderlyContact || '未知联系方式',
              feePeriod: (appData.feeStartDate && appData.feeEndDate) ? 
                `${appData.feeStartDate} 至 ${appData.feeEndDate}` : '未知费用期限',
              careLevel: '未知护理等级',
              bedNumber: appData.bedNumber || '未知床位',
              contract: appData.contractName || '未知合同',
              consultant: '未知顾问',
              caregiver: '未知护理员',
              checkoutDate: appData.checkOutDate || '未知退住日期',
              checkoutReason: appData.checkOutReason || '未知退住原因',
              remark: appData.remark || '无备注',
              applicantName: '护理员a',
              submitTime: appData.createTime || new Date().toLocaleString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit',
                hour12: false
              }).replace(/\//g, '-')
            }
            
            console.log('使用后端数据更新表单:', formData.value)
          }
        } catch (apiError) {
          console.error('后端API调用失败:', apiError)
        }
      }
    }
  } else {
    console.log('=== sessionStorage中没有数据，尝试从后端获取 ===')
    
    // 如果sessionStorage中没有数据，尝试从后端获取
    if (route.query.id) {
      try {
        const response = await getCheckoutApplicationDetail(route.query.id)
        console.log('后端返回的申请详情:', response)
        
        if (response.code === 200 && response.data) {
          const appData = response.data
          console.log('解析后的申请数据:', appData)
          
          // 使用后端数据更新表单
    formData.value = {
            elderlyNo: appData.checkOutNo || 'COUT' + route.query.id,
            elderlyName: appData.elderlyName || '未知老人',
            elderlyIdCard: appData.elderlyIdCard || '未知身份证',
            contact: appData.elderlyContact || '未知联系方式',
            feePeriod: (appData.feeStartDate && appData.feeEndDate) ? 
              `${appData.feeStartDate} 至 ${appData.feeEndDate}` : '未知费用期限',
            careLevel: '未知护理等级',
            bedNumber: appData.bedNumber || '未知床位',
            contract: appData.contractName || '未知合同',
            consultant: '未知顾问',
            caregiver: '未知护理员',
            checkoutDate: appData.checkOutDate || '未知退住日期',
            checkoutReason: appData.checkOutReason || '未知退住原因',
            remark: appData.remark || '无备注',
            applicantName: appData.creatorName || '护理员a',
            submitTime: appData.createTime || new Date().toLocaleString('zh-CN', {
              year: 'numeric',
              month: '2-digit',
              day: '2-digit',
              hour: '2-digit',
              minute: '2-digit',
              second: '2-digit',
              hour12: false
            }).replace(/\//g, '-')
          }
          
          console.log('使用后端数据更新表单:', formData.value)
        }
      } catch (apiError) {
        console.error('后端API调用失败:', apiError)
      }
    }
  }
  
  // 设置当前步骤
  if (route.query.step) {
    const stepNo = parseInt(route.query.step) || 2
    currentStep.value = stepNo - 1
    console.log('从URL参数设置的步骤号:', stepNo)
    console.log('步骤条索引:', currentStep.value)
    console.log('当前审批步骤:', currentStep.value + 1)
  }
  
  console.log('=== 审批页面加载完成 ===')
  console.log('最终表单数据:', formData.value)
  console.log('最终当前步骤:', currentStep.value)
})

// 查看合同
const viewContract = () => {
  ElMessage.info('查看合同文件：高启强长住合同.pdf')
}

// 返回
const handleBack = () => {
  // 返回到待办任务列表
  router.push('/xtgz/xtgz/tasks')
}


// 提交审批
const handleSubmit = async () => {
  if (!approveComment.value.trim()) {
    ElMessage.warning('请填写审批意见！')
    return
  }

  const resultText = approveResult.value === 'pass' ? '审批通过' : '审批拒绝'
  
  try {
    await ElMessageBox.confirm(
      `确认提交审批吗？\n审批结果：${resultText}\n审批意见：${approveComment.value}`,
      '确认提交',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }
    )
    
    // 准备提交数据
    const submitData = {
      opinion: approveResult.value === 'pass' ? '同意' : '拒绝', // 意见：审批通过=同意，审批拒绝=拒绝
      auditStatus: approveResult.value === 'pass' ? 1 : 2, // 审核状态：1=通过，2=拒绝
      bussniessId: route.query.id, // 业务ID
      type: route.query.type ? parseInt(route.query.type) : 1, // ✅ 业务类型（1=退住申请）
      extraField1: route.query.taskId || '', // ✅ 当前任务ID（步骤2）
      handleType: route.query.ptid ? parseInt(route.query.ptid) : null // ✅ 当前待办任务ID
    }
    
    console.log('=== 审批提交 ===')
    console.log('审批结果:', approveResult.value)
    console.log('审批意见:', approveComment.value)
    console.log('提交数据:', submitData)
    console.log('业务ID:', submitData.bussniessId)
    console.log('当前任务ID:', submitData.extraField1)
    console.log('当前待办任务ID:', submitData.handleType)
    
    // 调用后端API新增审批记录
    const response = await submitApproval(submitData)
    
    if (response.code === 200) {
      ElMessage.success('审批已提交！')
      
      // 根据审批结果跳转
      if (approveResult.value === 'pass') {
        // 审批通过：跳转到解除合同页面
        // ✅ 注意：审批完成后会生成第三步的待办任务，需要使用新的taskId和ptid
        setTimeout(() => {
          router.push({
            path: '/splccs/jcht',
            query: {
              id: route.query.id, // 传递业务ID
              // ✅ 审批完成后，系统会生成第三步的待办任务
              // 这里传递的参数会在解除合同页面中重新查询最新的待办任务
              taskId: '', // 清空，让解除合同页面重新查询
              ptid: '' // 清空，让解除合同页面重新查询
            }
          })
        }, 1000)
      } else {
        // 审批拒绝：直接返回待办任务列表
        setTimeout(() => {
          router.push({
            path: '/xtgz/xtgz/tasks'
          })
        }, 1000)
      }
    } else {
      ElMessage.error('审批提交失败：' + (response.msg || '未知错误'))
    }
    
  } catch (error) {
    if (error === 'cancel') {
      // 用户取消提交
      return
    }
    console.error('用户取消提交')
  }
}
</script>

<style scoped lang="scss">
.approval-page {
  min-height: 100%;
  background: linear-gradient(135deg, #e8f5e9 0%, #f1f8e9 50%, #fffde7 100%);
  padding: 20px;
  position: relative;
  overflow: hidden;

  // 装饰性背景元素
  &::before,
  &::after {
    content: '';
    position: absolute;
    border-radius: 50%;
    opacity: 0.3;
    pointer-events: none;
  }

  &::before {
    width: 400px;
    height: 400px;
    background: radial-gradient(circle, rgba(205, 220, 57, 0.3) 0%, transparent 70%);
    top: 100px;
    left: 10%;
  }

  &::after {
    width: 300px;
    height: 300px;
    background: radial-gradient(circle, rgba(139, 195, 74, 0.25) 0%, transparent 70%);
    top: 200px;
    right: 15%;
  }
}

.wrap {
  max-width: 1400px;
  margin: 0 auto;
  position: relative;
  z-index: 1;
}

/* 内容区域 */
.content {
  display: grid;
  grid-template-columns: 1fr 500px;
  gap: 20px;
  margin-bottom: 20px;
}

.left,
.right {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.card {
  background: white;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.card-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 20px;
  padding-bottom: 12px;
  border-bottom: 1px solid #e0e0e0;
}

/* 描述列表样式 */
:deep(.desc) {
  .desc-label {
    background: #fafafa;
    color: #666;
    font-weight: normal;
    text-align: right;
  }
}

/* 审批结果区域 */
.result-group {
  margin-bottom: 20px;

  &:last-child {
    margin-bottom: 0;
  }

  .label {
    font-size: 14px;
    color: #333;
    margin-bottom: 10px;
    font-weight: 500;

    .required {
      color: #f56c6c;
      margin-right: 4px;
    }
  }

  :deep(.el-radio-group) {
    display: flex;
    gap: 20px;
  }
}

/* 时间轴样式 */
.timeline {
  .timeline-item {
    display: flex;
    gap: 15px;
    margin-bottom: 25px;
    position: relative;

    &:last-child {
      margin-bottom: 0;
    }

    &:not(:last-child)::after {
      content: '';
      position: absolute;
      left: 21px;
      top: 45px;
      bottom: -25px;
      width: 2px;
      background: #e0e0e0;
    }
  }

  .timeline-icon {
    width: 42px;
    height: 42px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-size: 16px;
    flex-shrink: 0;

    &.success {
      background: #4caf50;
    }

    &.pending {
      background: #2196F3;
    }
  }

  .timeline-content {
    flex: 1;
    padding-top: 2px;
  }

  .timeline-header {
    display: flex;
    justify-content: space-between;
    margin-bottom: 8px;
    align-items: center;
  }

  .timeline-title {
    font-size: 14px;
    color: #333;
    font-weight: 500;
  }

  .timeline-date {
    font-size: 12px;
    color: #999;
    white-space: nowrap;
  }

  .timeline-user {
    font-size: 13px;
    color: #666;
    display: flex;
    align-items: center;
    gap: 8px;
  }
}

/* 底部按钮 */
.bottom-actions {
  display: flex;
  justify-content: center;
  gap: 15px;
  padding: 30px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .content {
    grid-template-columns: 1fr;
  }
}
</style>

